<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/03/11
 * Time: 10:18
 * @link http://www.lmterp.cn
 */

namespace app\common\behavior\order;

use app\common\behavior\BaseBehavior;
use app\common\model\Orders;
use app\common\model\WarehouseStock;
use app\common\service\orders\OrderService;
use app\common\service\product\StockService;

/**
 * 导入订单占用库存
 * Class LockStock
 * @package app\common\behavior\order
 */
class LockStock extends BaseBehavior
{
    /**
     * 处理订单
     * @param Orders $order
     * @date 2021/03/11
     * @author longli
     */
    public function run(Orders $order)
    {
        if(empty($order)) return;
        $status =  $order->getData('order_status');
        // 处理已完成订单
        if($status == Orders::ORDER_SUCCESS)
        {
            // 处理 FBA 订单
            if($order->isFBA())
            {
                StockService::orderFBA($order);
            }
            return;
        }
        // 分配仓库，占用库存
        if(!in_array($status, [Orders::ORDER_WAIT, Orders::ORDER_WAREHOUSE])) return;
        if($status == Orders::ORDER_WAIT)
        {
            \think\Console::call('order_warehouse', ["--ids={$order->order_id}"]);
            $order->refresh();
            if(empty($order->warehouse_id)) return;
        }
        if(!WarehouseStock::isEnoughBatch($order->warehouse_id, $order->detail->toArray()))
        {
            $order->order_status = Orders::ORDER_LACK;
            $order->save();
            return;
        }
        \think\Console::call('lock_stock', ['--action=order', "--type=lock", "--ids={$order->order_id}"]);
    }
}